<?php
/**
 * AdMinUser
 *
 * AdMinUser is the main user class. It extends the User Class
 * @author King Beto <apardo@adverit.com>
 * @version 1.0
 * @package AdMin Framework
 */

/**
 * AdMinUser is the main user class. It extends the User Class
 *
 * Here is an example of usage
 * <code>
 * require_once(DIR_CLASSES ."/User.php");
 *
 * // Login example:
 *
 * session_start();
 * $user = new adminUser();
 * $user->setDBLink($dbLink);
 * $user->readSession();
 *
 *
 * if ($_REQUEST['mod'] == "login") // with a post or a get
 * {
 *     $user->login($_POST['email'], $_POST['password']); // returns false if login fails
 * }
 *
 * // Suppose that we are editing another user data
 * $myUser = new AdMinUser();           // I create the object
 * $myUser->setDBLink($dbLink);         // I set the database connection
 * $myUser->get((int)$_GET['userID']);  // I fecth the user data (is is optional
 *                                      //  to update() or create())
 *
 * // Setting values
 * $myUser->set(array('levelID'         => (int)$_POST['levelID'],
 *                    'username'        => txt2sql($_POST['username'], false, $dbLink),
 *                    'userID_modified' => $user->getID()));
 *
 * // If the logged user has the permission to write a user's data
 * if ($user->isEnabledTo("write", "users"))
 * {
 *     (int)$_GET['userID']? $new->update() : $myUser->create();
 * }
 * </code>
 *
 * @package AdMin Framework
 */
class adminUser extends User
{
    // user permissions + roles permissions
    protected $_permissions = array();
    
    
    // Login con failed attempts y captcha:
    public function login($inputName, $inputPassword, $keepLoggedIn=false)
    {
        // Chequeo que la tabla tenga el campo paa controlar los intentos:
        $sql = 'SHOW COLUMNS FROM '.$this->_dbTable.' LIKE "failed_login_count"';
        $this->_mysqlQuery($sql, $result);
        if(mysql_num_rows($result) == 0)
        {
            $sql = 'ALTER TABLE '.$this->_dbTable.' ADD `failed_login_count` TINYINT UNSIGNED NOT NULL DEFAULT "0"';
            $this->_mysqlQuery($sql, $result);
        }
        
        // Logueo:
        if(parent::login($inputName, $inputPassword, $keepLoggedIn))
        {
            // Seteo en 0 el contador:
            $sql = 'UPDATE '.$this->_dbTable.' SET failed_login_count = 0 WHERE '.$this->_dbIndex.' = "'.$this->getID().'"';
            $this->_mysqlQuery($sql);
        
            return true;
        }
        else
        {
            // Si el usuario existe:
            $sql = 'SELECT '.$this->_dbIndex.', failed_login_count FROM '.$this->_dbTable .' WHERE '.$this->_dbUserName.'="'.$this->txt2sql($inputName).'"';
            $this->_mysqlQuery($sql, $result);
            if(mysql_num_rows($result) == 1)
            {
                list($userID, $failed_login_count) = mysql_fetch_row($result);
            
                $sql = 'UPDATE '.$this->_dbTable.' SET failed_login_count = failed_login_count+1 WHERE '.$this->_dbIndex.' = "'.$userID.'"';
                $this->_mysqlQuery($sql);
                $this->failed_login_count = $failed_login_count + 1;
            }
        }
        
        return false;
    }

    public function readSession()
    {
        if (parent::readSession() && $this->sessionManager->exists($this->sessionKey))
        {
            $this->loadAllPermissions();
            return 1;
        }
        return 0;
    }

    public function loadAllPermissions()
    {

        if($this->getID()=="") return;

        global $dbLink;

        $this->setDBLink($dbLink);
        // role permissions
        $sql = "SELECT distinct users_roles_permissions.module, permission FROM
                users_users_roles JOIN users_roles_permissions ON users_users_roles.roleID = users_roles_permissions.roleID
                WHERE userID=".$this->getID();

        $this->_mysqlQuery($sql, $result);
        while($row = mysql_fetch_array($result)) $this->_permissions[$row[0]][] = $row[1];

        $sql = "SELECT  module, permission FROM users_users_permissions WHERE userID=".$this->getID();
        // user permissions
        $this->_mysqlQuery($sql, $result);
        while($row = mysql_fetch_array($result)) $this->_permissions[$row[0]][] = $row[1];
        return $permissions;
    }

    public function getModuleUserPermissions($moduleID)
    {
        $sql = "SELECT permission FROM users_users_permissions WHERE userID='".$this->getID()."' AND module='".$moduleID."'";
        $this->_mysqlQuery($sql, $result);
        $permissions = array();
        while($row = mysql_fetch_array($result)) $permissions[] = $row[0];
        return $permissions;

    }

    public function setModuleUserPermissions($moduleID,$permissions)
    {
        if(!is_array($permissions)) return false;
        $this->_permissions = array();
        foreach($permissions as $permission)
                $this->_permissions[] = mysql_real_escape_string($permission);

        $sql = "DELETE FROM users_users_permissions WHERE userID='".$this->getID()."' AND module='".$moduleID."'";
        $this->_mysqlQuery($sql);
        if(count($permissions)==0) return;

        $sql = "INSERT INTO users_users_permissions (userID, module, permission) VALUES ";
        $values = array();
        foreach ($permissions as $p)
        {
            $values[] = "('".$this->getID()."','".$moduleID."','".$p."')";
        }
        $sql .= implode(",",$values);
        $this->_mysqlQuery($sql);
    }

    public function setRoles($roleIDs)
    {
        if(!is_array($roleIDs)) return false;
        $sql = "DELETE FROM users_users_roles WHERE userID='".$this->getID()."'";
        $this->_mysqlQuery($sql);
        if(count($roleIDs)==0) return;

        $sql = "INSERT INTO users_users_roles (userID, roleID) VALUES ";
        $values = array();
        foreach ($roleIDs as $roleID)
        {
            $values[] = "('".$this->getID()."','".$roleID."')";
        }
        $sql .= implode(",",$values);
        $this->_mysqlQuery($sql);
    }

    public function getRoles()
    {
        $sql = "SELECT roleID FROM users_users_roles WHERE userID='".$this->getID()."'";
        $this->_mysqlQuery($sql, $result);
        $roles = array();
        while($row = mysql_fetch_array($result)) $roles[] = $row[0];
        return $roles;
    }

    public function isEnabledTo($action, $moduleID)
    {
        $this->_debugLog(3,"User->isEnabledTo($action, $moduleID)");

        // superusers user pass directly
        if($this->isSuperuser()) return true;

        // Common users...
        if(isset($this->_permissions[$moduleID]) && in_array($action, $this->_permissions[$moduleID])) return true;

		// else...
        return false;
    }
    
    public function isSuperuser()
    {
        return ($this->superuser=="Y");
    }
}
